module ActsAsDynamic::Validations

  def validates_include(*args)
    options = args.last.is_a?(Hash) ? args.pop : {}
    attr_name = args.shift
    attr_values = args.shift || const_get(attr_name.to_s.pluralize.upcase)
    real_values = attr_values.first.is_a?(Array) ? attr_values.map(&:last) : attr_values
    options.reverse_update(:message => 'tiene un valor no permitido.')

    validates_each attr_name, options do |record, attr, value|
      record.errors.add(attr, options[:message]) unless real_values.include?(value)
    end
  end
  
  def validates_email(*args)
    options = args.last.is_a?(Hash) ? args.pop : {}
    emails = args.empty? ? [:email] : args
    options.reverse_update(:message => 'tiene un email incorrecto.')
    
    validates_each emails, options do |record, attr, value|
      record.errors.add(attr, options[:message]) if !value.blank? && !(value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
    end
  end

end

ActiveRecord::Base.extend ActsAsDynamic::Validations
